package com.gopay.checkorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.IcbcConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.icbc.ebank.pay.IcbcB2cMessage;
import com.gopay.common.domain.bank.icbc.ebank.query.res.CmsQueryB2CRes;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.BankInteractRemoteService;

public class CheckOrderIcbcB2cImpl implements BankOrderService {
	private final static Logger logger = LoggerFactory.getLogger("ICBC");

	@Resource(name = "bankClient")
	private BankInteractRemoteService bankClient;
	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String arg1) {
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		checkOrderResult.setOrderId(bankOrder.getOrderId());
		try {
			IcbcB2cMessage base = new IcbcB2cMessage();
			base.setOrderId(bankOrder.getOrderId());
			base.setBankOrderId(bankOrder.getOutOrderId());
			base.setBank(BankConstants.BANK_LOGO_ICBC);
			base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
			base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
			base.setLabel(bankOrder.getRemark2()); // 增加对账请求label
			Result result = new Result();

			result = bankClient.query(base);

			if (result == null || !result.isSuccess()) {
				logger.error("bankClient fail");
				
				if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
					BankCountDownLatch.failIncrease(bankOrder.getBankCode());
					checkOrderResult.setCommunicateError(true);
				}
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
			}

			CmsQueryB2CRes res = (CmsQueryB2CRes) result.getDefaultModel();
			
			// 订单查询返回对象为空
			if (res == null) {				
				logger.error("orderId: " + bankOrder.getOrderId()+ " errCode: " + ProcCodeConstants.PROC_CODE_100E6022+ " errorMessage: bis query is null");
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("银行返回对账结果为空");
				return checkOrderResult;
			}
			String returnCode = res.getEb().getPub().getRetCode(); // 订单查询交易返回码
			String retMsg = res.getEb().getPub().getRetMsg(); // 订单查询交易信息
			if (returnCode != null && !returnCode.equals(IcbcConstants.B2C_RETCODE_SUCCESS)) {
				// 查询订单错误
				logger.error("orderId: " + bankOrder.getOrderId()+ " returnCode:" + returnCode + " returnMessage:" + retMsg);
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
				checkOrderResult.setErrMsg(retMsg);
				return checkOrderResult;
			}
			String orderStatus = res.getEb().getOut().getRd().getResult(); // 订单状态
			if (orderStatus != null && !orderStatus.equals("")) {
				//成功处理
				if (orderStatus.equals(IcbcConstants.B2C_TRAN_ICBC_NC_DEAL_SUCC_1)){
					checkOrderResult.setSuccess(true);
					InAccInfo accInfo = new InAccInfo();
					accInfo.setOrderId(bankOrder.getOrderId());					
					String fen =res.getEb().getOut().getRd().getOrderAmt();//以分为单位
					BigDecimal amt = new BigDecimal(fen);
					accInfo.setAmount(amt.divide( new BigDecimal(100), 2, BigDecimal.ROUND_HALF_EVEN));
					accInfo.setRetCode("00");
					accInfo.setCardType(BankCardType.Unknown.toString());
					checkOrderResult.setAccInfo(accInfo);
					logger.error("工商银行B2C订单:" + bankOrder.getOutOrderId()+ ",交易成功返回信息：" + IcbcConstants.B2C_ICBC_SUCC_MESSAGE_1+ ",查到的订单状态:" + orderStatus);
				}else if (orderStatus.equals(IcbcConstants.B2C_TRAN_ICBC_NC_DEAL_SUCC_2)) {
					checkOrderResult.setSuccess(true);
					InAccInfo accInfo = new InAccInfo();
					accInfo.setOrderId(bankOrder.getOrderId());					
					String fen =res.getEb().getOut().getRd().getOrderAmt();//以分为单位
					BigDecimal amt = new BigDecimal(fen);
					accInfo.setAmount(amt.divide( new BigDecimal(100), 2, BigDecimal.ROUND_HALF_EVEN));
					accInfo.setRetCode("00");
					accInfo.setCardType(BankCardType.Unknown.toString());
					checkOrderResult.setAccInfo(accInfo);					
					logger.error("工商银行B2C订单:" + bankOrder.getOutOrderId()+ ",交易成功返回信息：" + IcbcConstants.B2C_ICBC_SUCC_MESSAGE_2+ ",查到的订单状态:" + orderStatus);
				}
				//失败处理
				else if (orderStatus.equals(IcbcConstants.B2C_TRAN_ICBC_NC_DEAL_FAIL)) {
					checkOrderResult.setBankFailure(true);// 银行订单状态为失败
					checkOrderResult.setErrMsg("银行返回交易失败");
					logger.error("工商银行B2C订单:" +  bankOrder.getOutOrderId()+ ",交易失败返回信息：" + IcbcConstants.B2C_ICBC_FAIL_MESSAGE+ ",查到的订单状态:" + orderStatus);
				}
				//不处理
				else if (orderStatus.equals(IcbcConstants.B2C_TRAN_ICBC_NC_DEAL_DEALING_1)) {
					logger.error("工商银行B2C订单:" + bankOrder.getOutOrderId()+ ",交易返回信息：" + IcbcConstants.B2C_ICBC_DEALING_MESSAGE_1+ ",暂不进行账务处理,查到的订单状态:" + orderStatus);
					checkOrderResult.setErrMsg("银行返回支付交易可疑");

				} else if (orderStatus.equals(IcbcConstants.B2C_TRAN_ICBC_NC_DEAL_DEALING_2)) {
					logger.error("工商银行B2C订单:" + bankOrder.getOutOrderId()+ ",交易返回信息：" + IcbcConstants.B2C_ICBC_DEALING_MESSAGE_2+ ",暂不进行账务处理,查到的订单状态:" + orderStatus);
					checkOrderResult.setErrMsg("银行返回等待答复");
				}
			}
			// 没有查到订单
			else {
				logger.error(" ICBC B2C orderId:" + bankOrder.getOrderId()+ ",returnMsg: 银行返回订单未查到");
				checkOrderResult.setErrMsg("银行返回订单未查到");
			}
			return checkOrderResult;
		} catch (Exception e) {
			logger.error("bankClient fail: ", e);
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("银行对账异常");
			return checkOrderResult;
		}
	}
	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}
}
